import { createRouter, createWebHistory } from "vue-router"
import Cookies from "js-cookie"
import store from "@/store";

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', redirect: '/home'},
    { path: '/login', name: 'login', meta: { title: '登录' },component: () => import('@/views/login.vue')},
    { path: '/home', name: 'home', meta: {title: '首页',}, component: () => import('@/views/home.vue') },

    { path: "/simulation", name: "simulation", meta: { title: '模拟考试', keepAlive: true }, component: () => import('@/views/exam/simulation.vue') },
    { path: "/chapter", name: "chapter", meta: { title: '章节练习', keepAlive: true }, component: () => import('@/views/exam/chapter.vue') },


    { path: "/question/:id", name: "question", meta: { title: '开始练习' }, component: () => import('@/views/exam/question.vue') },
    { path: '/exam-record', name: 'exam-record', meta: { title: '考试记录' }, component: () => import('@/views/exam/exam-record.vue') },
    { path: '/course', name: 'course', meta: { title: '课程' }, component: () => import('@/views/course/course.vue') },
    { path: '/course-catalogue/:id', name: 'course-catalogue', meta: { title: '课程详情' }, component: () => import('@/views/course/course-catalogue.vue') },
    { path: '/mall', name: 'mall', meta: { title: '商城',}, component: () => import('@/views/mall/mall.vue') },
    //个人中心
    { path: '/my', name: 'my', meta: { title: '个人中心' }, component: () => import('@/views/my/my.vue')},
    { path: '/info', name: 'info', meta: { title: '用户信息'}, component: () => import('@/views/my/info.vue') },
    { path: '/about', name: 'about', meta: { title: '关于我们'}, component: () => import('@/views/my/about.vue') },

    { path: '/material', name: 'material', meta: { title: '资料库' }, component: () => import('@/views/material/material.vue') },
    { path: '/wxAuth', name: 'wx-auth', meta: { title: '微信授权', auth: true }, component: () => import('@/views/auth/wx-auth.vue') },

  ]
});

/**
 * 路由守卫
 */
router.beforeEach((to, from, next) => {
  let isAuthenticated = false;
  // Cookies.remove("token")
  if (Cookies.get('token')) {
    isAuthenticated = true
  }
  if (to.path !== '/login') {
    if (isAuthenticated){
      //初始化数据
      store.dispatch({ type: "initApp" }).then(() => {
        // if (!to.matched.length) {
        //   console.log("to.matched.length=",to.matched.length)
        // }
        // setTimeout(() => {
        //   store.commit("updateState", { appIsRender: true, appIsLogin: true });
        // }, 600);
        next();
      });
    }else {
      next("/login");
    }
  }else {
    next();
  }
});

export default router
